<html>
  <head>
    <title>Main view</title>
    <link href="/static/css/main.css" rel="stylesheet" type="text/css"/>

	<script language="javascript" src="/static/json2.js"> </script>
<!--	<script language="javascript" src="http://maps.google.com/maps?file=js&v=2&amp;key=ABQIAAAAqtIM8-INTT7ZcmQlUzEdshTwM0brOpm-All5BF6PoaKBxRWWERSM696MtKRJGn-A6H4lRpYxTHyL5g"> </script>-->
	<script language="javascript" src="http://maps.google.com/maps?file=js&v=2&amp;key=ABQIAAAAqtIM8-INTT7ZcmQlUzEdshQ42DU5ZLFVDxnCT7wBDm1c7LTPvhSNFXTyD4hUat2Jf7wM2hF8HTRniA"> </script>

    <script type="text/javascript">

/********************************************************************************************** 
Google Maps Methods                                                         
**********************************************************************************************/
    var map;
    var calls = new Array();
    
    function getInfoWindowContent(lat,long,isNew,marker) {
      // Provide the html for the InfoWindow (form)
      var html = "<html><head></head><body><strong>Call Details</strong><form><table>" +
        "<tr><td>Call ID:</td> <td><input type='text' id='callName' value=''/> </td> </tr>" +
        "<tr><td>Description:</td> <td><input type='text' id='callDescription' value=''/></td> </tr>" +
        "<tr><td></td><td><input type='button' value='Save' onClick='saveCall(" + lat + "," + long + "," + isNew + ")'/></td> " +
        "<td><input type='submit' value='Hide' onClick='hideCall(" + lat + "," + long + ");map.removeOverlay(" + marker + ");'/></tr></table></form></body></html>";            
      return html;
    }

    function createMarker(latlng, ResourceLetter) {
      // Create a marker on the Map, when clicked show InfoWindow
      // This MUST remain together - see pitfull 3 @ http://econym.googlepages.com/basic1.htm
      // Credit Mike Williams (http://groups.google.com/group/Google-Maps-API/browse_thread/thread/d9eba6b76493658a#)      

      var Icon = new GIcon(G_DEFAULT_ICON);
      if (!ResourceLetter) {
        // Blue dot - ? for Calls
        Icon.image = "/static/icons/markerBlank.png";
        markerOptions = { icon:Icon };
        var marker = new GMarker(latlng, markerOptions);
        var html = getInfoWindowContent(latlng.y, latlng.x, 1, marker)
      }else{
        Icon.image = "/static/icons/marker" + ResourceLetter + ".png";
        markerOptions = { icon:Icon };
        var marker = new GMarker(latlng, markerOptions);
        var html = "Resource Letter: " + ResourceLetter;
        // TODO: Lookup Resource Details here
      }

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
        server.doGetCallInformation(latlng.y,latlng.x, onUpdateCallInfo);
      });
      return marker;
    }

    function load() {
      // Create the map, specify that when map clicked create a marker and save (empty) call at that location
      map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng (36.14357, -5.35391), 15);

      GEvent.addListener(map, "click", function(marker, latlng) {
        marker = createMarker(latlng);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(getInfoWindowContent(latlng.y, latlng.x, 1, marker));
        saveCall(latlng.y, latlng.x, 0);
      }); 

      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
    }
    
/********************************************************************************************** 
Methods to handle Resources & Calls
**********************************************************************************************/

    function updateResourceInformation(response) {
      // Download all resources, add to list for user to choose
      var el = null;
      var div = document.getElementById("resources");

      if (response == -1) {
        alert ("ERROR: Unable to retrieve latest resource information from Server in updateResourceInformation()");
        return False;
      } else {
        div.innerHTML="";
        for (id = 0; id < response.length; id++) {
          el = document.createElement("input");
          el.type="checkbox";
          el.name="showDevices";
          el.value=response[id]["letterIdentifier"];
          div.appendChild(el);
          div.appendChild(document.createTextNode(response[id]["deviceId"]));
          div.appendChild(document.createElement("br"));
        }
      }
    }

    function updateMapMarkers(response) {
      // Download all active calls from server, clear map and put one marker per call on map
      if (response == -1) {
        alert ("ERROR: Unable to retrieve latest call location information from Server in updateMapMarkers()");
        return False;
      } else {
        map.clearOverlays();
        for (id = 0; id < response.length; id++) {
          if (response[id]["call"] == 1) {
            marker = createMarker(new GLatLng (response[id]["x"], response[id]["y"]));
          }else if(response[id]["call"] == 0) {
            marker = createMarker(new GLatLng (response[id]["x"], response[id]["y"]), response[id]["letter"]);
          }else{
            alert ("ERROR: Corruption in updateMapMarkers");
            return False;
          }
          map.addOverlay(marker);
        }  
      }
    }

    function onUpdateCallInfo(response) {
      // Callback from server, set value in InfoWindow for name and description when InfoWindow opens
      if (document.getElementById("callName")) {
        document.getElementById("callName").value = unescape(response['name']);
        document.getElementById("callDescription").value = unescape(response['description']);
      }else{
        return False;
      }
      return True;
    }

    function hideCall(lat, lng, marker) {
      // Change a call to Active=False, i.e. hide from map
      alert("Test");
      server.doHideCall(lat,lng, reportResult);
      //map.removeOverlay(marker);
    }
      
    function saveCall(lat,lng,isNew) {
      // Updates a call, or adds it if no call at exact location
      if (document.getElementById("callName")) {
        var callName = escape(document.getElementById("callName").value);
        var callDescription = escape(document.getElementById("callDescription").value); 
      }else{
        var callName = "";
        var callDescription = "";
      }
      server.doSaveCall(lat, lng, callName, callDescription, reportResult);
      if (isNew == 1) {
        map.closeInfoWindow();
        document.getElementById("message").innerHTML = "Waiting for server to add call " + callName + ".";
      }
    }

/********************************************************************************************** 
Functions used by various methods                                                  
**********************************************************************************************/

      function reportResult(result) {
        // Take response from server, show in "Status" box
        document.getElementById("message").innerHTML = result;
      }
      
/**********************************************************************************************
            Google AJAX Code                                                                  
            [From the Google App Engine intro to RPC Article]                                 
**********************************************************************************************/
    //
    // As mentioned at http://en.wikipedia.org/wiki/XMLHttpRequest
    //
    if( !window.XMLHttpRequest ) XMLHttpRequest = function()
    {
      try{ return new ActiveXObject("Msxml2.XMLHTTP.6.0") }catch(e){}
      try{ return new ActiveXObject("Msxml2.XMLHTTP.3.0") }catch(e){}
      try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
      try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
      throw new Error("Could not find an XMLHttpRequest alternative.")
    };

    //
    // Makes an AJAX request to a local server function w/ optional arguments
    //
    // functionName: the name of the server's AJAX function to call
    // opt_argv: an Array of arguments for the AJAX function
    //
    function Request(function_name, opt_argv) {

      if (!opt_argv)
        opt_argv = new Array();
     
      // Find if the last arg is a callback function; save it
      var callback = null;
      var len = opt_argv.length;
      if (len > 0 && typeof opt_argv[len-1] == 'function') {
        callback = opt_argv[len-1];
        opt_argv.length--;
      }
      var async = (callback != null);
     
      // Encode the arguments in to a URI
      var query = 'action=' + encodeURIComponent(function_name);
      for (var i = 0; i < opt_argv.length; i++) {
        var key = 'arg' + i;
        var val = JSON.stringify(opt_argv[i]);
        query += '&' + key + '=' + encodeURIComponent(val);
      }
      query += '&time=' + new Date().getTime(); // IE cache workaround

      // Create an XMLHttpRequest 'GET' request w/ an optional callback handler 
      var req = new XMLHttpRequest();
      req.open('GET', '/rpc?' + query, async);
     
      if (async) {
        req.onreadystatechange = function() {
          if(req.readyState == 4 && req.status == 200) {
            var response = null;
            try {
             response = JSON.parse(req.responseText);
            } catch (e) {
             response = req.responseText;
            }
            callback(response);
          }
        }
      }
     
      // Make the actual request
      req.send(null);
    }

    // Adds a stub function that will pass the arguments to the AJAX call 
    function InstallFunction(obj, functionName) {
      obj[functionName] = function() { Request(functionName, arguments); }
    }

    // Server object that will contain the callable methods
    var server = {};

    // Insert 'Add' as the name of a callable method
    InstallFunction(server, 'doSaveCall');
    InstallFunction(server, 'doHideCall');
    InstallFunction(server, 'doGetCallInformation');
    InstallFunction(server, 'doGetResourceInformation');

    InstallFunction(server, 'doUpdateMarkers');


    // Handy "macro"
    function $(id){
      return document.getElementById(id);
    }

/**********************************************************************************************  
            Code to run events regularly                                                      
            [From http://www.whatstyle.net/articles/36/javascript_periodical_executer]        
**********************************************************************************************/

	Function.prototype.executePeriodically = function (){
	  var s = this;
	  if (typeof arguments[0].callee != 'undefined'){
	    var arquments = arguments[0];
	  } else {
	  var arquments = arguments;
	 }
	 
	var delay = arquments[0];
	var timesToExecute = arquments[1];
	this.__INTERVAL__ = null;
	 
	var args = [];
	for (var i=2; i<arquments.length; i++){ args.push(arquments[i]); }
	 
	s.apply(this,args);
	 
	if (this.__INTERVAL__)
	  clearTimeout(this.__INTERVAL__);
	 
	if (--timesToExecute > 0){
	  this.__INTERVAL__ = setTimeout (function (){
	    arquments[1] = timesToExecute;
	    s.executePeriodically(arquments);
	  },delay);
	}
	return s;
	}
    </script>
	
  </head><!-- load(); updateTable.executePeriodically(15000,5,0); -->
  <body onload="load();" onunload="GUnload()">

    <div class="wrapper" id="wrapper">
      <div class="header" class="header">
        <h1>Dispatcher Center</h1>
        <div class="login">
          <b>{{ display_user|escape }}</b> | <a href="{{ logout_url }}">Sign Out</a>    
        </div>
      </div>
      <div class="map" id="map"></div>
      <div class="list" id="list">
        <h2>Available Resources</h2>
        <small><a href="#" onclick="server.doGetResourceInformation(updateResourceInformation);">update</a></small><br />
        <div id="resources">
        </div>
        <p><small><strong>Note:</strong> This is under construction. At the moment, ALL available resources are shown on the map</small></p>
      </div>
    </div>
    <div><span style="color: white;">Status Updates</span></div> <!-- horrid hack, layout requires it tho -->
    <div class="bottom">

    <small><a href="#" onclick="server.doUpdateMarkers(updateMapMarkers);">Update map with latest locations</a> </small>
    <h2>Status</h2>
    <small><p id="message">Awaiting Update</p></small>

    </div>

  </body>
</html>